package p.ithorns.integration.hz.core;

import com.hazelcast.cluster.Address;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.map.IMap;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

/**
 * SumEntryProcessor
 * TODO ithorns
 *
 * @author Ht.L
 * @date 2023-11-21 09:56
 * @since 1.0.0
 */
@Slf4j
public class SumTask implements Callable<Integer>, Serializable, HazelcastInstanceAware {

    private transient HazelcastInstance hz;

    private final int value;

    private Address member;

    private IMap<String, Integer> map;

    public SumTask(int value) {
        this.value = value;
    }

    @Override
    public synchronized void setHazelcastInstance(HazelcastInstance hz) {
        this.hz = hz;
        this.map = hz.getMap("map");
        this.member = hz.getCluster().getLocalMember().getAddress();
    }

    @Override
    public Integer call() throws Exception {
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        int result = 0;
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            int last = entry.getValue();
            result = last + value;
            map.set(key, result);
            // log.info("{} 执行计算: {} + {} ->  {}",  member, last, value, result);
        }
        return result;
    }

}